package com.lyang.mall.biz.order.listener;

import com.lyang.mall.api.order.constant.OrderConstant;
import com.lyang.mall.api.order.entity.Stock;
import com.lyang.mall.api.order.entity.StockExample;
import com.lyang.mall.biz.order.mapper.StockMapper;
import com.lyang.mall.biz.order.util.RedisUtil;
import com.lyang.mall.common.util.BeanMapConvertUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.List;
import java.util.Map;

@WebListener
public class StockDataToRedisListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        StockMapper stockMapper = (StockMapper)applicationContext.getBean(StockMapper.class);
        List<Stock> stockList = stockMapper.selectByExample(new StockExample());
        if(!CollectionUtils.isEmpty(stockList)){
            for(Stock stock : stockList){
                //Map<String,Object> cacheData = BeanMapConvertUtil.beanToMap(stock);
                RedisUtil.hset(OrderConstant.REDIS_KEY_STOCK+stock.getId(), "count",String.valueOf(stock.getCount()));
                RedisUtil.hset(OrderConstant.REDIS_KEY_STOCK+stock.getId(), "sale",String.valueOf(stock.getSale()));
                RedisUtil.hset(OrderConstant.REDIS_KEY_STOCK+stock.getId(), "name",String.valueOf(stock.getName()));
                RedisUtil.hset(OrderConstant.REDIS_KEY_STOCK+stock.getId(), "version",String.valueOf(stock.getVersion()));

            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
